package com.nhjf.common.util.freemaker;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMakerTools {

	/***************************************************************************
	 * 生成静态页面方法
	 * 
	 * @param context
	 *            servlet上下文
	 * @param templatePath
	 *            模板加载路径
	 * @param ftl
	 *            模板文件名
	 * @param outputPath
	 *            生成静态页面路径
	 * @param targetHtmlName
	 *            生成文件名
	 * @param map
	 *            数据
	 * @throws IOException
	 * @throws TemplateException
	 */
	@SuppressWarnings("unchecked")
	public void createHtmls(
					ServletContext context, 
					String templatePath, 
					String ftl,
					String outputPath, 
					String targetHtmlName, 
					Map map)throws IOException, TemplateException {
		Configuration freemarkerCfg = new Configuration();
		// 加载模板
		freemarkerCfg.setServletContextForTemplateLoading(context, "/"+ templatePath);
		freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");

		Template template = freemarkerCfg.getTemplate(ftl, "UTF-8");
		template.setEncoding("UTF-8");

		BufferedWriter buff = new BufferedWriter(new FileWriter(outputPath+ targetHtmlName));

		File htmlFile = new File(outputPath + targetHtmlName);

		Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
		template.process(map, out);

		buff.close();
		out.flush();
		out.close();
	}
}